package com.lxx.utils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

public class Utils {
	
	public static void main(String[] args) {
		rename();
	}
	
	// 遍历文件夹，将所有html后缀的文件，改为jsp，并且添加头部代码
	public static void rename() {
		String extStr = "<%@ page language=\"java\" contentType=\"text/html; charset=UTF-8\"\r\n" + 
				"    pageEncoding=\"UTF-8\"%>\r\n" + 
				"<%\r\n" + 
				"	String contextPath = application.getContextPath();\r\n" + 
				"	pageContext.setAttribute(\"path\", contextPath);\r\n" + 
				"%>";
		String fdir = "D:\\code\\personalprojects\\jbase\\src\\main\\webapp\\WEB-INF\\pages";
		FileUtils.listFiles(new File(fdir), FileFilterUtils.suffixFileFilter(".html"), null)
		.forEach(f -> {
			String newFilePath = f.getAbsolutePath().substring(0, f.getAbsolutePath().length() - 5)
					+ ".jsp";
			
			File newFile = new File(newFilePath);
			
			try {
				List<String> lines = Files.readLines(f, Charsets.UTF_8);
				StringBuilder content = new StringBuilder(extStr);
				content.append("\r\n");
				lines.forEach(e -> {
					content.append(e).append("\r\n");
				});
				Files.write(content.toString().getBytes("UTF-8"), newFile);
				f.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			System.out.println(newFilePath);
			
		});
	}

}
